import contextlib

class LookingClass:

    def __enter__(self):
        """
        __enter__ with 进入方法, 做某些操作
        此处把系统的输出函数指向一反向输出函数
        """
        import sys
        self.original_write = sys.stdout.write
        # 系统的输出修改为自定义的输出
        sys.stdout.write = self.reverse_write
        return 'JABBEREOCKY'

    def reverse_write(self, text):
        self.original_write(text[::-1])

    def __exit__(self, exc_type, exc_value, traceback):
        """
        __exit__ with语句结束清理方法

        把反向输出函数修改为正常输出

        Args:
            exc_type ([type]): 异常类
            exc_value ([type]): 异常实例
            traceback ([type]): 追踪栈
        """
        import sys
        sys.stdout.write = self.original_write
        if exc_type is ZeroDivisionError:
            print('Please do not divide by zero!')
            return True

@contextlib.contextmanager
def looking_fun():
    import sys
    original_write = sys.stdout.write

    def reverse_write(text):
        original_write(text[::-1])
    sys.stdout.write = reverse_write
    msg = ''
    try:
        yield 'JABBERWORCY'
    except ZeroDivisionError:
        msg = 'Please do not divide by zero'
    finally:
        sys.stdout.write = original_write
        if msg:
            print(msg)



if __name__ == "__main__":
    # when for loop not break, run else
    print("for loop")
    for i in range(10):
        print(i)
    else:
        print("normal end, without break")
    i = 0
    print("run while loop")
    while i < 10:
        print(i)
        i+=1
    else:
        print("normal end, withoud break")

    print("run try clause")
    try:
        print("running try")
    except Exception as e:
        print(e)
    else:
        print("normal exit, no exception")



